package uploadpic;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doGet(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			upload(req);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		req.getRequestDispatcher("/jsp/uploadpicB.jsp").forward(req, resp);
	}
	
	private void upload(HttpServletRequest req) throws FileUploadException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items = upload.parseRequest(req);
		int i = 1;
		for(FileItem item: items) {
			if(item.isFormField()) {
				String value = item.getString();
				value = new String(value.getBytes("ISO-8859-1"),"UTF-8");
				System.out.println(value);
				
				req.setAttribute("code", value);
				
			}else {
				String filename = item.getName();
				System.out.println(filename);
				
				filename = getFname(item);
				
				FileOutputStream fos = new FileOutputStream("F:\\practice\\temp\\"+filename);
				InputStream is = item.getInputStream();
				int len = -1;
				byte[] b = new byte[1024*1024];
				while(-1!=(len = is.read(b))) {
					fos.write(b,0,len);
				}
				fos.flush();
				fos.close();
				is.close();
				fos=null;
				is=null;
				req.setAttribute("fn" + i++, filename);
			}
		}
	}
	
	private String getFname(FileItem item) {
		String fn = item.getName();
		String uuid = UUID.randomUUID().toString();
		return uuid+fn.substring(fn.lastIndexOf("."));
	}
}